package config;

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;
import java.util.Arrays;

public class SystemConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{AppConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{MvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {
        registration.setMultipartConfig(new MultipartConfigElement("d:/aaa", 10240000, 102400000, 1024000));
    }

    /**
     * 注册字符编码过滤器，此过滤器就是针对DispatchServlet而言的
     * 也就是说请求能进到DispatchServlet，此过滤器就生效，不进mvc，此字符编码过滤器就不生效
     * <p>
     * 此过滤器可以解决接收前端传递过来的数据的乱码问题
     *
     * @return
     */
    @Override
    protected Filter[] getServletFilters() {
        Filter charEncodingFilter = getCharacterEncodingFilter();
        Filter corsFilter = getCorsFilter();

        return new Filter[]{charEncodingFilter, corsFilter};
    }

    private Filter getCharacterEncodingFilter() {
        CharacterEncodingFilter charEncodingFilter = new CharacterEncodingFilter();
        charEncodingFilter.setEncoding("UTF-8");
        charEncodingFilter.setForceEncoding(true);
        return charEncodingFilter;
    }

    private Filter getCorsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //使用add开头或set开头的方法进行设置
        corsConfiguration.addAllowedOrigin("http://127.0.0.1:5500");
        corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.setMaxAge(3600L);
        corsConfiguration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        CorsFilter corsFilter = new CorsFilter(corsConfigurationSource);
        return corsFilter;
    }
}
